#include "ShaderLoader.h"

GLuint ShaderLoader::loadShader(GLenum shaderType, const char* pSource) 
{
    GLuint shader = glCreateShader(shaderType);
    if (shader) 
	{
        glShaderSource(shader, 1, &pSource, NULL);
        glCompileShader(shader);

        GLint compiled = 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);

        if (!compiled) 
		{
			printf(((shaderType == GL_VERTEX_SHADER) ? "Vertex shader error: ":"Frag shader error: "));

            int infoLen = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
			if (infoLen > 1)
			{
				char* buf = new char[infoLen];

				glGetShaderInfoLog(shader, infoLen, NULL, buf);
				printf(buf);

				delete[] buf;
			}
			else printf("Program error: %s\n", "<unknown>");;

            glDeleteShader(shader);
            shader = 0;
        }
    }
    return shader;
}
GLuint ShaderLoader::loadShader(GLenum shaderType, std::ifstream& File)
{
	File.seekg (0, std::ios::end);
	int length = File.tellg();
	File.seekg (0, std::ios::beg);

	char* source = new char[length];
	File.read(source, length);

	return loadShader(shaderType, source);
	
	delete[] source;
}
GLuint ShaderLoader::createProgram(GLuint vertexShader, GLuint pixelShader) 
{
    GLuint program = glCreateProgram();
    if (program) 
	{
        glAttachShader(program, vertexShader);
        glAttachShader(program, pixelShader);

        glLinkProgram(program);
        GLint linkStatus = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);

        if (linkStatus != GL_TRUE) 
		{
			int infoLen = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);
            if (infoLen) 
			{
                char* buf = new char[infoLen];
                
				glGetProgramInfoLog(program, infoLen, NULL, buf);
				printf("Program error: %s\n", buf);
                
                delete[] buf;
            }

            glDeleteProgram(program);
            program = 0;
        }
    }
    return program;
}
